package com.maple.p2pclient.utils;


import android.content.Context;

import org.webrtc.Camera1Enumerator;
import org.webrtc.Camera2Enumerator;
import org.webrtc.CameraEnumerator;
import org.webrtc.CameraVideoCapturer;
import org.webrtc.MediaConstraints;
import org.webrtc.PeerConnection;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class WebRTCUtils {

    public static CameraVideoCapturer createVideoCapture(Context context) {
        CameraEnumerator enumerator = Camera2Enumerator.isSupported(context)? new Camera2Enumerator(context) : new Camera1Enumerator();
        String[] deviceNames = enumerator.getDeviceNames();
        //前置
        for (String name : deviceNames) {
            if(enumerator.isFrontFacing(name)) {
                return enumerator.createCapturer(name,null);
            }
        }
        //后置
        for (String name : deviceNames) {
            if(enumerator.isBackFacing(name)) {
                return enumerator.createCapturer(name,null);
            }
        }
        return null;
    }

    public static PeerConnection.RTCConfiguration createRTCConfiguration() {
        List<PeerConnection.IceServer> iceServers = new ArrayList<>();
        PeerConnection.IceServer stun = PeerConnection.IceServer.builder("stun:stun.l.google.com:19302").createIceServer();
        iceServers.add(stun);
//        PeerConnection.IceServer turn = PeerConnection.IceServer.builder("turn:turn.bistri.com:80").setUsername("homeo").setPassword("homeo").createIceServer();?
        PeerConnection.IceServer turn = PeerConnection.IceServer.builder("turn:turn.107.6.243.171:3478").setUsername("123456").setPassword("123456").createIceServer();
        iceServers.add(turn);
        PeerConnection.RTCConfiguration config = new PeerConnection.RTCConfiguration(iceServers);
        if(checkSdpSemanticsSupport()) {
            config.sdpSemantics = PeerConnection.SdpSemantics.UNIFIED_PLAN;
        }
        return config;
    }

    private static boolean checkSdpSemanticsSupport() {
        try {
            // 尝试访问 PeerConnection.RTCConfiguration 的 sdpSemantics 属性
            Field field = PeerConnection.RTCConfiguration.class.getDeclaredField("sdpSemantics");
            field.setAccessible(true);  // 使私有属性可访问
            return true;  // 如果能成功访问，说明支持 sdpSemantics 属性
        } catch (NoSuchFieldException e) {
            // 属性不存在，说明不支持
            return false;
        }
    }

    public static MediaConstraints buildAudioConstraints() {
        MediaConstraints mediaConstraints = new MediaConstraints();
        List<MediaConstraints.KeyValuePair> items = Arrays.asList(
                new MediaConstraints.KeyValuePair("googEchoCancellation", Boolean.toString(true)),
                new MediaConstraints.KeyValuePair("googAutoGainControl", Boolean.toString(true)),
                new MediaConstraints.KeyValuePair("googHighpassFilter", Boolean.toString(true)),
                new MediaConstraints.KeyValuePair("googNoiseSuppression", Boolean.toString(true)),
                new MediaConstraints.KeyValuePair("googTypingNoiseDetection", Boolean.toString(true))
        );

        mediaConstraints.optional.addAll(items);
        return mediaConstraints;
    }

    /**
     * 转换AnswerSdp
     * @param offerSdp offerSdp：创建offer时生成的sdp
     * @param answerSdp answerSdp：网络请求srs服务器返回的sdp
     * @return 转换后的AnswerSdp
     */
    public static String convertAnswerSdp(String offerSdp, String answerSdp) {
        if (offerSdp == null || answerSdp == null) {
            return "";
        }
        int indexOfOfferVideo = offerSdp.indexOf("m=video");
        int indexOfOfferAudio = offerSdp.indexOf("m=audio");
        if (indexOfOfferVideo == -1 || indexOfOfferAudio == -1) {
            return answerSdp;
        }

        int indexOfAnswerVideo = answerSdp.indexOf("m=video");
        int indexOfAnswerAudio = answerSdp.indexOf("m=audio");
        if (indexOfAnswerVideo == -1 || indexOfAnswerAudio == -1) {
            return answerSdp;
        }

        boolean isFirstOfferVideo = indexOfOfferVideo < indexOfOfferAudio;
        boolean isFirstAnswerVideo = indexOfAnswerVideo < indexOfAnswerAudio;

        if (isFirstOfferVideo == isFirstAnswerVideo) {
            // 顺序一致
            return answerSdp;
        } else {
            // 需要调换顺序
            return answerSdp.substring(0, Math.min(indexOfAnswerVideo, indexOfAnswerAudio)) +
                    answerSdp.substring(Math.max(indexOfAnswerVideo, indexOfOfferVideo)) +
                    answerSdp.substring(Math.min(indexOfAnswerVideo, indexOfAnswerAudio), Math.max(indexOfAnswerVideo, indexOfOfferVideo));
        }
    }
}
